﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using RestFullChatAJAX.Models;
using RestFullChatAJAX.Models.DAO;
using System.Threading;
using Newtonsoft.Json.Linq;

namespace RestFullChatAJAX.Controllers
{
    public class StateController : ApiController
    {
        private static List<List<NotifyInfo>> StateChangeList = new List<List<NotifyInfo>>();
        private static object lockState = new object();

        // GET api/State/username
        public List<NotifyInfo> GetState(String id)
        {
            int index = -1;
            do
            {
                //Interval check notify
                Thread.Yield();
                index = IndexManager.FindStoreIndex(id);
                if (index == -1)
                    return null;
                lock (lockState)
                {
                    //Has change in state
                    if (StateChangeList[index].Count > 0)
                    {
                        List<NotifyInfo> lst = new List<NotifyInfo>();
                        lst.AddRange(StateChangeList[index]);
                        StateChangeList[index].RemoveRange(0,StateChangeList[index].Count);
                        return lst;
                    }
                }
            } while (true);                        
        }

        public static void Add()
        {
            lock (lockState)
            {
                StateChangeList.Add(new List<NotifyInfo>());
            }
        }

        public static void Remove(int index)
        {
            lock (lockState)
            {
                StateChangeList.RemoveAt(index);
            }
        }

        public static void AddToStore(int index, String actor, String type)
        {
            lock (lockState)
            {
                StateChangeList[index].Add(new NotifyInfo(actor, type));
            }
        }
    }
}
